from appointment_app import models
from django.db.models import Q
from appointment_app.service import check_place_service

# 新增检测任务组
def addGroupCheckTask(formData):
    res = models.group_check_task.objects.create(**formData)
    return res


# 查询检测任务组
def getGroupCheckTaskList(queryForm):
    # 根据地点名，查询检测点的uuid集合
    place_uuid_list = []
    check_place_obj_list = check_place_service.getCheckPlaceByUuid(queryForm)
    if check_place_obj_list:
        for cpo in check_place_obj_list:
            place_uuid_list.append(cpo.uuid)
    if place_uuid_list:
        res = models.group_check_task.objects.filter(
            place_uuid__in=place_uuid_list
        ).order_by("-id")
    return res


# 更新检测任务组
def updateGroupCheckTask(formData):
    res = models.group_check_task.objects.filter(uuid=formData["uuid"]).update(
        **formData
    )
    return res


# 根据uuid查询检测任务组
def getGroupCheckTask(uuid):
    res = models.group_check_task.objects.filter(uuid=uuid).first()
    return res


# 根据place_uuid查询检测任务组
def getGroupCheckTaskByPlaceUuid(place_uuid):
    res = models.group_check_task.objects.filter(place_uuid=place_uuid)
    return res


# 删除检测任务组
def delGroupCheckTask(uuid):
    res = models.group_check_task.objects.filter(uuid=uuid).delete()
    return res

# 根据uuid更新可预约数量，如果可预约，则used_num+1并返回True，否则，预约人数已满，返回False
def updateUsedNumByUuid(uuid):
    gct_obj = getGroupCheckTask(uuid)
    isOrder = False # 是否可预约
    if gct_obj:
        sum_num = gct_obj.sum_num
        used_num = gct_obj.used_num
        sub_num = sum_num - used_num
        if sub_num > 0:
            # 更新used_num的值
            used_num += 1
            formData = {'uuid':uuid, 'used_num':used_num}
            res = updateGroupCheckTask(formData)
            if res:
                isOrder = True
    return isOrder